from django.shortcuts import render
from libs.captcha.captcha import captcha

from django_redis import get_redis_connection

from django.http import HttpResponse

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializxer
from rest_framework.response import Response
from rest_framework import status
from random import randint
from libs.yuntongxun.sms import CCP

# Create your views here.
# 图片验证码
class RegisterImageCodeView(APIView):
    """
        生成验证码
        GET verifications/imagecodes/(?P<image_code_id>.+)/
        需要通过JS生成一个唯一码,以确保后台对图片进行校验
        """
    def get(self,request,image_code_id):
        """
            通过第三方库，生成图片和验证码，我们需要队验证码进行Redis保存

            1.创建图片和验证码
            2.通过Redis进行保存验证码，需要再设置里添加 验证码数据库选项
            3.将图片返回

        """
        # 创建图片和验证码
        text,image=captcha.generate_captcha()
        # 通过Redis进行保存
        redis_conn=get_redis_connection('code')
        redis_conn.setex('img_%s'%image_code_id,60,text)
        # 将图片返回，图片是二进制，通过HttpResponse返回
        return HttpResponse(image,content_type='image/jpeg')

class RegisterSMSCodeView(GenericAPIView):
    """
        获取短信验证码
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx
    获取短信验证码,首先需要校验 验证码

     1.创建序列化器，定义text和image_code_id
     2.Redis判断该用户是否频繁获取
     3.生成短信验证码
     4.Redis增加记录
     5.发送短信
     6.返回响应
    """
    serializer_class = RegisterSMSCodeSerializxer
    def get(self,request,mobile):

        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        redis_conn=get_redis_connection('code')

        if redis_conn.get('sms_flag_%s'%mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)

        sms_code='%06d'%randint(0,999999)
        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)
        redis_conn.setex('sms_flag_%s'%mobile,60,1)
        ccp=CCP()
        ccp.send_template_sms(mobile,[sms_code,5],1)
        return Response({'message':'ok'})



